// components/uploadImg/index.js
const componentBehavior = require('../../js/common/ComponentBehavior')

import {
  upload
} from '../../js/modules/material.js'
import {util} from '../../js/util';
Component({
  lifetimes: {
    attached() {
      let array = this.data.photolist.concat(this.data.photo);
      this.setData({
        photolist:array
      })
    }
  },
  /**
   * 组件的属性列表
   */
  properties: {
    num:{
      type:Number,
      value:1          
    },
    photo:{
      type:Array,
      value:[]
    },
    profileToken:String
  },

  /**
   * 组件的初始数据
   */
  data: {
    photolist:[],
    virtualImageList:[]
  },

  behaviors: [componentBehavior],

  /**
   * 组件的方法列表
   */
  methods: {
    bindUploadPhoto:function(){
      var that = this;
      let limitNum = that.data.num;
      if (this.data.photolist.length >= limitNum) {
        util.tips(`最多只能上传${limitNum}张`);
        return;
      }
      var count = limitNum - this.data.photolist.length;
      wx.chooseImage({
        count: count,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: function (res) {
          var tempFilePaths = res.tempFilePaths;
          // console.log(tempFilePaths,'-====');
          tempFilePaths.map(function (item) {
            that.data.photolist.push(item);
          })
          that.setData({
            photolist: that.data.photolist
          });
          var datax = {num:1008,type:1,tempFilePaths:res.tempFilePaths,profileToken:that.data.profileToken};
          upload.upload_image_server(datax, function (image_list) {
            if (image_list.length==0){
              util.alert("上传失败");
              return;
            }
            image_list.map(function (item) {
              that.data.virtualImageList.push(item);
              that.triggerEvent('bindUploadPhoto', {
                list: that.data.virtualImageList
              })
            });
          })
        }
      });
    },
    /**
     * 删除照片
     */
    onDelPhotoEvent:function(e){ 
      let n = e.currentTarget.dataset.imgidx;
      let {photolist,virtualImageList} = this.data;
      photolist.splice(n,1);
      virtualImageList.splice(n,1);
      this.setData({
        photolist,
        virtualImageList
      },()=>{
        this.triggerEvent('onDelPhotoEvent', {
          list: this.data.virtualImageList
        })
      })
    },
  }
})
